#!/bin/bash

# Function to display help
show_help() {
    echo "Usage: script/dev [OPTIONS]"
    echo ""
    echo "Options:"
    echo "  -p --profile VALUE    Start with the given dev profile"
    echo "  -d --devtools         Start with devtools opened"
    echo "  -r --rust-log VALUE   Set the log level for Rust dependencies (error, warn, info, debug, trace)"
    echo "  -l --atuin-log VALUE  Set the log level for the Atuin backend (error, warn, info, debug, trace)"
    echo "  -h --help             Display this help message and exit"
    echo ""
    echo "Default log levels:"
    echo "  Rust backend: info"
    echo "  Atuin backend: debug"
    echo ""
}

# Parse command line arguments
PROFILE=""
DEVTOOLS=""
RUST_LOG="info"
ATUIN_LOG="debug"
while [[ $# -gt 0 ]]; do
    case $1 in
        -p|--profile)
            PROFILE="$2"
            shift 2
            ;;
        -d|--devtools)
            DEVTOOLS="1"
            shift
            ;;
        -h|--help)
            show_help
            exit 0
            ;;
        -r|--rust-log)
            RUST_LOG="$2"
            shift 2
            ;;
        -l|--atuin-log)
            ATUIN_LOG="$2"
            shift 2
            ;;
        *)
            echo "Unknown argument: $1"
            echo ""
            show_help
            exit 1
            ;;
    esac
done

# Function to check if a port is available
check_port() {
    nc -z localhost $1 >/dev/null 2>&1
    return $?
}

# Start with default port
PORT=1420
export RUST_LOG
export ATUIN_LOG

# If default port is in use, find next available port
if check_port $PORT; then
    while check_port $PORT; do
        PORT=$((PORT + 1))
    done

    # Create config file with new port
    CONFIG_FILE="backend/tauri-port-${PORT}.conf.json"
    cat > "$CONFIG_FILE" << EOF
{
  "build": {
    "devUrl": "http://localhost:${PORT}"
  }
}
EOF

    # Run Tauri with custom config and optional profile
    if [ -n "$PROFILE" ]; then
        if [ -n "$DEVTOOLS" ]; then
            DEV_PREFIX="$PROFILE" DEVTOOLS="$DEVTOOLS" pnpm run tauri dev --config "$CONFIG_FILE"
        else
            DEV_PREFIX="$PROFILE" pnpm run tauri dev --config "$CONFIG_FILE"
        fi
    else
        if [ -n "$DEVTOOLS" ]; then
            DEVTOOLS="$DEVTOOLS" pnpm run tauri dev --config "$CONFIG_FILE"
        else
            pnpm run tauri dev --config "$CONFIG_FILE"
        fi
    fi
else
    # Run Tauri with default config and optional profile
    if [ -n "$PROFILE" ]; then
        if [ -n "$DEVTOOLS" ]; then
            DEV_PREFIX="$PROFILE" DEVTOOLS="$DEVTOOLS" pnpm run tauri dev
        else
            DEV_PREFIX="$PROFILE" pnpm run tauri dev
        fi
    else
        if [ -n "$DEVTOOLS" ]; then
            DEVTOOLS="$DEVTOOLS" pnpm run tauri dev
        else
            pnpm run tauri dev
        fi
    fi
fi
